/*
对话聊天的路由组件
*/
import React, { Component } from 'react'
import { NavBar, List, InputItem, Grid, Icon } from 'antd-mobile'
import { connect } from 'react-redux'
import { sendMsg, readMsg } from '../../redux/actions'
import QueueAnim from "rc-queue-anim"
const Item = List.Item



class Chat extends Component {

  state = {
    content: '',
    isShow: false, //是否显示表情列表
    emojis: []
  }

  // 在第一次render执行之前回调, 初始化标枪别表数据
  componentWillMount() {
    const emojis = [
      '😀',
      '😃',
      '😄',
      '😁',
      '😆',
      '😅',
      '🤣',
      '😂',
      '🙂',
      '🙃',
      '😉',
      '😊',
      '😇',
      '🥰',
      '😍',
      '🤩',
      '😘',
      '😗',
      '😚',
      '😙',
      '😋',
      '😛',
      '😜',
      '🤪',
      '😝',
      '🤑',
      '🤗',
      '🤭',
      '🤫',
      '🤔',
      '🤐',
      '🤨',
      '😐',
      '😑',
      '😶',
      '😏',
      '😒',
      '🙄',
      '😬',
      '🤥',
      '😌',
      '😔',
      '😪',
      '🤤',
      '😴',
      '😷',
      '🤒',
      '🤕',
      '🤢',
      '🤮',
      '🤧',
      '🥵',
      '🥶',
      '🥴',
      '😵',
      '🤯',
      '🤠',
      '🥳',
      '😎',
      '🤓',
      '🧐',
      '😕',
      '😟',
      '🙁',
      '😮',
      '😯',
      '😲',
      '😳',
      '🥺',
      '😦',
      '😧',
      '😨',
      '😰',
      '😥',
      '😢',
      '😭',
    ]
    this.emojis = emojis.map(e =>
      ({ text: e })
    )
  }
  componentDidMount = () => {
    window.scrollTo(0, document.body.scrollHeight)
  }
  componentDidUpdate = () => {
    window.scrollTo(0, document.body.scrollHeight)
  }
  componentWillUnmount = () => {
    const count = this.props.chat.unReadCount
    if (count) {
      // 更新当前的消息为已读
      const from = this.props.match.params.userid
      const to = this.props.user._id
      this.props.readMsg(from, to)
    }
  }

  handleSend = () => {
    const from = this.props.user._id
    const to = this.props.match.params.userid
    const content = this.state.content.trim() //去掉头部空白尾部空白
    // 发送请求
    if (content) {
      this.props.sendMsg({ from, to, content })
    }
    // 清除输入数据
    this.setState({ content: '', isShow: false })
  }

  toggle = () => {
    const isShow = !this.state.isShow
    this.setState({ isShow })
    if (isShow) {
      setTimeout(() => {
        window.dispatchEvent(new Event('resize'))
      }, 0);
    }
  }
  render() {
    const { user, chat } = this.props
    const { users, chatMsgs } = chat

    // 计算当前聊天的chatID
    const meID = user._id
    if (!users[meID]) {   //如果还没有获取数据，不作任何显示
      return null
    }

    // 计算当前聊天的chat_id
    const userid = user._id
    const targetid = this.props.match.params.userid
    const chatId = [userid, targetid].sort().join('_')
    // 对chatMsgs进行过滤
    const msgs = chatMsgs.filter(msg => chatId === msg.chat_id)

    // 得到目标的头像和username
    const targetUser = users[targetid]
    const headerIcon = targetUser.header ? require(`../../assets/headers/${targetUser.header}.png`) : null
    const username = targetUser.username

    return (
      <div id='chat-page' >
        <NavBar
          onLeftClick={() => this.props.history.goBack()}
          icon={<Icon type="left" />}
          style={{ position: "fixed", width: '100%', top: '0', zIndex: 1000 }}
        >{username}</NavBar>
        <List style={{ margin: '40px 0' }}>
          <QueueAnim type='left' delay={100}>
          {
            msgs.map(msg => {
              if (msg.to === userid) { //对方发给我的
                return (<Item key={msg._id}
                  thumb={headerIcon}>
                  {msg.content}
                </Item>)
              } else { //我发的
                return (<Item className='chat-me' extra='我' key={msg._id}>
                  {msg.content}
                </Item>)
              }
            })
          }
          </QueueAnim>
          
        </List>
        <div className='am-tab-bar'>
          <InputItem
            placeholder="请输入"
            value={this.state.content}
            onFocus={() => { this.setState({ isShow: false }) }}
            extra={
              <span>
                <span onClick={this.toggle} style={{ marginRight: '10px' }}>😁</span>
                <span onClick={this.handleSend}>发送</span>
              </span>
            }
            onChange={v => this.setState({ content: v })}
          />
          {this.state.isShow ? <Grid
            data={this.emojis}
            columnNum={8}
            carouselMaxRow={4}
            isCarousel={true}
            onClick={(item) => {
              this.setState({ content: this.state.content + item.text })
            }}
          /> : null}

        </div>
      </div>
    )
  }
}

export default connect(
  state => ({ user: state.user, chat: state.chat }),
  { sendMsg,readMsg }
)(Chat)